package com.dxy.netty.handlerchain;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @Description 测试handler链的服务器
 * <p>
 * 参考1：netty入站与出站（处理器链调用机制）
 * https://blog.csdn.net/PacosonSWJTU/article/details/126796461
 * <p>
 * 参考2：Netty - [出站、入站机制]
 * https://blog.csdn.net/ZEUS00456/article/details/127347346
 * <p>
 * 参考3：netty 之 入站、出站、handler顺序
 * https://www.jianshu.com/p/0bd66bd460e4
 * @Author dangxianyue
 * @Date 2023/1/8 15:56
 */
public class NettyHandlerChainServer {

    private final int port;

    public NettyHandlerChainServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) {
        try {
            new NettyHandlerChainServer(8089).run();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void run() throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new NettyServerInitializer()); // 自定义一个初始化类
            // 自动服务器
            ChannelFuture channelFuture = serverBootstrap.bind(this.port).sync();
            System.out.println("服务器启动成功");
            // 监听关闭
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    /**
     * @author xiao tang
     * @version 1.0.0
     * @Description 初始化器
     * @createTime 2022年09月10日
     */
    static class NettyServerInitializer extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            // 入站handler，把字节型数据解码为long型
            // 注意：入站处理器执行顺序与处理器添加顺序相同
            // MyByte2LongDecoder2
            // NettyHandlerChainServerHandler
            //pipeline.addLast(new MyByte2LongDecoder()); // MyByte2LongDecoder 与 MyByte2LongDecoder2 等价
            pipeline.addLast(new MyByte2LongDecoder2());

            // 出站handler,  把long型数据编码为字节(编码器)
            // 注意：出战处理器执行顺序与处理器添加顺序相反
            // NettyHandlerChainServerHandler
            // MyLong2ByteEncoder
            pipeline.addLast(new MyLong2ByteEncoder());

            // 添加业务逻辑handler
            pipeline.addLast(new NettyHandlerChainServerHandler());

            System.out.println("NettyServerInitializer.initChannel 执行成功.");
        }
    }
}
